import 'dart:convert';
import 'dart:math';

import 'package:number_spark_flutter/network/ns_api.dart';
import 'package:number_spark_flutter/pages/ns_mine/ns_mine_logic.dart';
import 'package:number_spark_flutter/routes/ns_app_pages.dart';
import 'package:number_spark_flutter/utils/ns_log_report_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:number_spark_flutter/utils/ns_user_utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

const String idFreeCount = 'freeCount';

class NSHomeLogic extends GetxController {
  int selectedIndex = 10;
  RefreshController refreshController = RefreshController(initialRefresh: false);

  @override
  void onInit() {
    super.onInit();
    NSLogReportUtils.stat(page: NSLogPages.nsHome);
  }

  onRefresh() async {
    refreshController.refreshCompleted();
  }

  doClickShare() {
    Get.toNamed(NSRoutes.publish);
  }

  doClickDoubleGame() async {
    if (NSUserUtils.getUserDoubleGameFreeCount() > 0) {
      Get.toNamed(NSRoutes.double);
      NSUserUtils.setUserDoubleGameFreeCount(NSUserUtils.getUserDoubleGameFreeCount() - 1);
      update([idFreeCount]);
    } else {
      if (Get.isRegistered<NSMineLogic>()) {
        NSMineLogic mineLogic = Get.find();
        if ((mineLogic.userInfoModel.availableCoins ?? 0) >= 5) {
          BotToast.showLoading();
          Map<String, dynamic> params = {'outlay': 5, 'source': 'iap'};
          NSResponseData responseData = await NSApi.consumeCoin.post(params);
          BotToast.closeAllLoading();
          if (responseData.isSuccess()) {
            mineLogic.onGetUserInfo();
            Get.toNamed(NSRoutes.coinShop);
          }
        } else {
          Get.toNamed(NSRoutes.coinShop);
        }
      } else {
        Get.toNamed(NSRoutes.coinShop);
      }
    }
  }
}
